package com.by.datasource.handler.mybatisPlus;

import com.by.toolkit.utils.SplitterUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collections;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

@Slf4j
public class GroupConcatConvertSetLongHandler extends BaseTypeHandler<Set<Long>> {
    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, Set<Long> contentList, JdbcType jdbcType) throws SQLException {
        //如果是空不进行设置值
        if (Objects.isNull(contentList)) {
            return;
        }
        preparedStatement.setString(i, SplitterUtil.EN_COMMA_JOINER.join(contentList));
    }

    @Override
    public Set<Long> getNullableResult(ResultSet resultSet, String s) throws SQLException {
        String content = resultSet.getString(s);
        if (StringUtils.isBlank(content)) {
            return Collections.emptySet();
        }
        return SplitterUtil.EN_COMMA_SPLITTER.omitEmptyStrings()
                .splitToList(content)
                .stream()
                .map(Long::parseLong)
                .collect(Collectors.toSet());
    }

    @Override
    public Set<Long> getNullableResult(ResultSet resultSet, int i) throws SQLException {
        String content = resultSet.getString(i);
        if (StringUtils.isBlank(content)) {
            return Collections.emptySet();
        }
        return SplitterUtil.EN_COMMA_SPLITTER.omitEmptyStrings()
                .splitToList(content)
                .stream()
                .map(Long::parseLong)
                .collect(Collectors.toSet());
    }

    @Override
    public Set<Long> getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        String content = callableStatement.getString(i);
        if (StringUtils.isBlank(content)) {
            return Collections.emptySet();
        }
        return SplitterUtil.EN_COMMA_SPLITTER.omitEmptyStrings()
                .splitToList(content)
                .stream()
                .map(Long::parseLong)
                .collect(Collectors.toSet());
    }
}
